#Jupyter magic command to improve teh display of charts in the Notebook
%matplotlib inline

5. Report writing and scenario results#

ModelFlow, standard pandas routines and other python libraries like Matplotlib and Plotly can be used to visualize and compare dataframes and therefore the results from scenarios – as indeed has been done in the preceding paragraphs.

In addition, ModelFlow also provides several specific routines that make such comparisons easier.

5.1. Prepare python session#

from modelclass import model 
import modelmf       # Add useful features to pandas dataframes 
                     # using utlities initially developed for modelflow

model.widescreen()   # These modelflow commands ensure that outputs from modelflow play well with Jupyter Notebook
model.scroll_off()

%load_ext autoreload   
%autoreload 2

5.1.1. Load model object and simulation results from Scenario Analysis Chapter#

mpak,_ = model.modelload(r'..\models\mpakwScenarios.pcim', run=False)
file read:  C:\modelflow manual\papers\mfbook\content\models\mpakwScenarios.pcim

5.2. The Keep option#

The Keep option facilitates the comparison of results from different scenarios run on a give model object. In each of the simulations executed above, the keep option was activated. This causes the results from each simulation to be stored in the model object in a DataFrame that can be identified by the descriptor given to it.

The Keep option facilitates the comparison of results from different scenarios run on a give model object. In each of the simulations executed above, the keep option was activated. This causes the results from each simulation to be stored in the model object in a DataFrame that can be identified by the descriptor given to it.

By default all variables are kept, if the user wishes to restrict the kept variables to a sub-set, they can do so by setting the keep_variables when the simulation is run, where

For example:

mpak(CTempExogAllKG,2020,2040,keep='2.5% increase in C 2025-27 -- exog whole period --KG=True',keep_variables='PAKNYGDPMKTPKN PAKNE*KN PAKEM*')

would run a simulation between 2020 AND 2040 CALLED 2.5% increase in C 2025-27 – exog whole period –KG=True but keep only the variables that matched the search string in keep_variables.

5.3. The .keep_plot() method#

The keep_plot method can be used to plot and compare results from the various scenarios that had been run earlier using the keep= option.

By default the results across all scenarios for each selected variables will be shown on one chart at a time.

mpak.keep_plot('PAKNYGDPMKTPCN PAKNECONPRVTKN PAKNEIMPGNFSKN',  legend=True)
#show for each variable on a separate chart the results from each kept scenario
../../_images/1967972fc5456f06c8d179fcad03caf4be088a90519d8dcc0cc12d901349986c.png ../../_images/c51e113c451f4785d4f96662094958b24ff1cc3f373c225964e9d30ccea7f6c4.png ../../_images/ec608f66933af77b0ffe73cf45e9bbd01a11c0d3806cbe2a45aab8e1a2a50432.png
{'PAKNYGDPMKTPCN': <Figure size 1000x600 with 1 Axes>,
 'PAKNECONPRVTKN': <Figure size 1000x600 with 1 Axes>,
 'PAKNEIMPGNFSKN': <Figure size 1000x600 with 1 Axes>}

5.3.1. keep_plot() options#

The variables to be displayed are listed as first argument. Variable names can include wildcards (using * for any string and ? for any character).

Transformation of data displayed:

showtype=

Use this operator

‘level’ (default)

No transformation

‘growth’

The growth rate in percent

‘change’

The yearly change (\(\Delta\))

legend placement

legend=

Use this operator

False (default)

The legends are placed at the end of the corresponding line

True

The legends are places in a legend box

Often it is useful to compare the scenario results with the baseline result. This is done with the diff argument.

diff=

Use this operator

False (default)

All entries in the keep_solution dictionary are displayed

True

The difference to the first entry is shown.

It can also be useful to compare the scenario results with the baseline result measured in percent. This is done with the diffpct argument.

diffpct=

Use this operator

False (default)

All entries in the keep_solution dictionary is displayed

True

The difference in percent to the first entry is shown

Note

'keep_plot() and .keep_plot_multi() return a python object that points to the in memory version of the rendered figure(s). This object can be used to modify the graph (see examples towards the end of this chapter.

savefig='[path/]<prefix>.<extension>' Will create a number of files with the charts.
The files will be saved location with name <path>/<prefix><variable name>.<extension>
The extension determines the format of the saved file: pdf, svg and png are the most common extensions.

5.3.2. An example using the diff=TRUE option#

When diff=True (or 1) results will be shown all of the selected scenarios presented as the change in selected variables with respect to the first scenario – in this instance the scenario saved with the name baseline.

Note in this instance `baseline` and `basedf` are the same because they were defined that way.  However, there is nothing in the system that guarantees that the first `keep` scenario will be the baseline or the `basedf` scenario.
mpak.keep_plot('PAKNYGDPMKTPCN PAKNECONPRVTKN PAKNEIMPGNFSKN', diff=1, legend=True)
../../_images/9d94278170bb421a0f7e4d31867fd60962f4f193fbc2f7e92028687dc165909b.png ../../_images/2bb7018d7f250c21b89bfaf9f97438338fa6ac4a6aece1fbb598d2bfddecd7e5.png ../../_images/b126dded42445d05753b9edf5073975c14e29bdbb641068825c419bc97a5bb21.png
{'PAKNYGDPMKTPCN': <Figure size 1000x600 with 1 Axes>,
 'PAKNECONPRVTKN': <Figure size 1000x600 with 1 Axes>,
 'PAKNEIMPGNFSKN': <Figure size 1000x600 with 1 Axes>}
```{index} single: Scenarios: Keep_plot examples - showtype=growth

5.3.3. The showtype option#

In this example the difference with respect first 'keep scenario baseline values are once again shown. This time the showtype option has been set to growth. As a result the data is displayed as the difference in the growth rate.

mpak.keep_plot('PAKNYGDPMKTPCN PAKNEIMPGNFSKN', diff=1,showtype='growth', legend=True)
../../_images/f9439fd6b19fa28a7c609b0c5aa9b2ff079ad21f37006d6708ff38cb0019728e.png ../../_images/fbb1e330f639178e84609acf218dca6fcfd6dcc87a4c91a26cdd2e6ada2c3677.png
{'PAKNYGDPMKTPCN': <Figure size 1000x600 with 1 Axes>,
 'PAKNEIMPGNFSKN': <Figure size 1000x600 with 1 Axes>}
```{index} single: Scenarios: Keep_plot examples - showtype=diffpct

5.3.4. The diffpct option#

Setting diffpct=True instructs .keep_plot() to display the data as a percent deviation from the first kept scenario, which in this case was the baseline scenario.

mpak.keep_plot('PAKNYGDPMKTPCN  PAKNEIMPGNFSKN', diffpct=1,legend="Change in level as a % of first keep scenario")
../../_images/6d2974db05da220838638a8cbbcbafb889cd6dbac59b729c55d150971765a6b4.png ../../_images/620601c770e23c1ee413923328831ba366b95beaefa97f561a9c6f4a9d35060d.png
{'PAKNYGDPMKTPCN': <Figure size 1000x600 with 1 Axes>,
 'PAKNEIMPGNFSKN': <Figure size 1000x600 with 1 Axes>}

5.3.4.1. Differences in percent of baseline values#

In this plot, the same results are presented, but as percent deviations from the baseline values of the displayed data.

mpak.keep_plot('PAKNYGDPMKTPCN PAKNECONPRVTKN ', diffpct=1,showtype='level', legend=True)
../../_images/6d2974db05da220838638a8cbbcbafb889cd6dbac59b729c55d150971765a6b4.png ../../_images/34b9ef982c7a6e02e0f4f76a7c7fd82d60e7e9ed611132a7f0b0386c5d6e9cde.png
{'PAKNYGDPMKTPCN': <Figure size 1000x600 with 1 Axes>,
 'PAKNECONPRVTKN': <Figure size 1000x600 with 1 Axes>}

5.3.5. The .keep_switch() method#

The .keep_switch() method restricts the number of scenarios on which subsequent calls to .keep_plot() (and .keep_plot_multi()) are executed on. .keep_switch() can be passed a list of scenarios or using a wildcard selector.

5.3.5.1. The .keep_solutions.keys() method#

The .keep_solutions.keys() method generates a list of the solutions that have been kept previously.

mpak.keep_solutions.keys()
dict_keys(['Baseline', '$25 increase in oil prices 2025-27', '2.5% increase in C 2025-40', '2.5% increase in C 2025-27 -- exog whole period', '2.5% increase in C 2025-27 -- exog whole period --KG=True', '2.5% increase in C 2025-27 -- temporarily exogenized', '1% of GDP increase in FDI and private investment (AF shock)'])

To specify exactly which scenarios to show in a keep_plot, the scenarios= option of .keepswitch() must be initialized with a “|” delimited string of the names of the scenarios (retrieved above) that are to be displayed.

By placing the .keepswitch() in a with clause the scenario restriction will only apply to indented lines that follow the with construct.

with mpak.keepswitch(scenarios='2.5% increase in C 2025-40|2.5% increase in C 2025-27 -- exog whole period|2.5% increase in C 2025-27 -- exog whole period --KG=True|2.5% increase in C 2025-27 -- temporarily exogenized'):
    mpak.keep_plot('PAKNYGDPMKTPKN PAKGGBALOVRLCN PAKGGDEBTTOTLCN',start=2000,end=2040,diff=False,showtype='growth',legend=True);
../../_images/7e7c4ad122e908f3cdd51b02a4a099743aaea4dc90a5d1077a54262a79ce37f2.png ../../_images/0255ebdc1f67b42f0ce08d72bc53decea83ba85c70ffa11c52782bc5daf92ebb.png

5.3.5.2. Keepswitch with wildcard selection#

Below a series of plots are generated using a wildcard selector in the keepswitch clause.

with mpak.keepswitch(scenarios='*2025*'):
    mpak.keep_plot('PAKNYGDPMKTPKN PAKNECONPRVTKN',showtype='growth',legend=True,start=2020,end=2040);
../../_images/7d1aa1ca7b80bc840d25f12a2679f4c190d82eecf72cf6f12a4d247df9830ea2.png ../../_images/53ecd99caf80c691a952bb6131692e98a3a3fe68aac682da277baf00fe32b45e.png

5.4. The .keep_plot_multi() method#

The .keep_plot_multi() method allows several charts to be displayed in a grid. The size of each chart can be set with the size=(w,h) option, where the units of with and height are in centimetres.

with mpak.set_smpl(2000,2040):
    with mpak.keepswitch(scenarios="baseline *exog*"):
        var_figs = mpak.keep_plot_multi('PAKNYGDPMKTPKN PAKNECONPRVTKN PAKNEGDIFTOTKN PAKNEIMPGNFSKN PAKNEEXPGNFSKN',2010,2040,keep_dim=0,legend=1
                                ,size=(20,20) ,diffpct=True,title='Scenario Comparison'  );
../../_images/110b073013bb48ae907f8e787aab3de274c42258c568c7e059e8bf4220299939.png ../../_images/d0207b592c68e6eba3c886c8bf3e4c0e913066366b28e2733a47ee824b534250.png ../../_images/cc8753508708321924a1cc407bbc1e235cbb4e25eb114ffe1f16af04929078bb.png

As indicated earlier both keep_plot() and keep_plot_multi() return a variable that can be used to embellish or modify the figures produced by the automatic routines.

For example the charts can be resized.

var_figs.set_size_inches(15,10)
var_figs
../../_images/942463b2392d04bf8798e6948527acd7058699e22b6f7f05fc8aab9d44cb3774.png

Individual charts can be deleted from the grid.

Note

The grid representation of the individual charts is returned as a 0-based vector of charts. Thus the first figure is the zeroeth and the second is the first.

5.4.1. Delete a chart from the grid#

A chart can be deleted from the grid by referencing it and calling the .remove() method.

var_figs.axes[1].remove()
var_figs
../../_images/c483f408fcff51079cbcc81aa84540d823255f538b1ccd5481169442e4c7c0c8.png

The same mechanism can be used to revise the titles of the indidividual charts and annotate them.

var_figs.axes[0].set_title('Impact of a 2.5% increase in C using exog method');    # many properties can be set afterward 
var_figs.axes[1].set_title('Impact of a 2.5% increase in C using temporary exog method');
var_figs
../../_images/2856465f79752c035b6f040dbf5cff576b1a91a38125712b5ff258e2e9dac234.png
var_figs.axes[0].set_xlabel('Year')
var_figs.axes[0].set_ylabel('Change percent\nchange in level',fontsize=10)
var_figs.axes[0].yaxis.set_label_coords(-0.1,1.02)
var_figs.axes[0].xaxis.set_label_coords(.95,-.06)
var_figs
../../_images/9b6dc54d4dcf59ca08c931665f1833136f746748e0ed700924b6ed817d7ea6ee.png

Variables pointing to the individual charts can be defined and used to make modifications to individual charts within the overall figure.

fig1=var_figs.axes[0]
fig2=var_figs.axes[1]
fig2.set_ylabel('Percent change\nin level',fontsize=10)
fig2.yaxis.set_label_coords(-0.1,1.02) #place axes labels
fig2.xaxis.set_label_coords(.95,-.06)



fig2.text(2040.,0.4, 'Some text in a box', 
          color='yellow',bbox=dict(facecolor='red', alpha=0.5));
fig2.text(2040.,0.1, 'Some nice text', 
          style='italic',color='green');
          
var_figs
          
../../_images/e7227c0c6374d0c6873e4ddd760defd9fe1205eeb13ca25fd9be73e97e9e4672.png